package client

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

// Client CapCut API客户端
type Client struct {
	BaseURL    string
	HTTPClient *http.Client
}

// Response API响应结构
type Response struct {
	Code int             `json:"code"`
	Msg  string          `json:"msg"`
	Data json.RawMessage `json:"data,omitempty"`
}

// NewClient 创建新的客户端
func NewClient(baseURL string) *Client {
	return &Client{
		BaseURL: baseURL,
		HTTPClient: &http.Client{
			Timeout: 30 * time.Second,
		},
	}
}

// doRequest 执行HTTP请求
func (c *Client) doRequest(method, path string, params url.Values) (json.RawMessage, error) {
	// 构建URL
	u, err := url.Parse(c.BaseURL)
	if err != nil {
		return nil, err
	}
	u.Path = path
	u.RawQuery = params.Encode()

	// 创建请求
	req, err := http.NewRequest(method, u.String(), nil)
	if err != nil {
		return nil, err
	}

	// 发送请求
	resp, err := c.HTTPClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	// 解析响应
	var apiResp Response
	if err := json.NewDecoder(resp.Body).Decode(&apiResp); err != nil {
		return nil, err
	}

	// 检查响应状态
	if apiResp.Code != 0 {
		return nil, fmt.Errorf("API error: %s (code: %d)", apiResp.Msg, apiResp.Code)
	}

	return apiResp.Data, nil
}

// CreateDraft 创建草稿
func (c *Client) CreateDraft(width, height int, draftID string) (string, string, error) {
	// 构建参数
	params := url.Values{}
	params.Set("width", strconv.Itoa(width))
	params.Set("height", strconv.Itoa(height))
	if draftID != "" {
		params.Set("draft_id", draftID)
	}

	// 发送请求
	data, err := c.doRequest(http.MethodGet, "/create_draft", params)
	if err != nil {
		return "", "", err
	}

	// 解析响应
	var result struct {
		DraftID  string `json:"draft_id"`
		DraftURL string `json:"draft_url"`
	}
	if err := json.Unmarshal(data, &result); err != nil {
		return "", "", err
	}

	return result.DraftID, result.DraftURL, nil
}

// QueryDraftStatus 查询草稿状态
func (c *Client) QueryDraftStatus(draftID string) (string, int, error) {
	// 构建参数
	params := url.Values{}
	params.Set("draft_id", draftID)

	// 发送请求
	data, err := c.doRequest(http.MethodGet, "/query_draft_status", params)
	if err != nil {
		return "", 0, err
	}

	// 解析响应
	var result struct {
		DraftID string `json:"draft_id"`
		Status  string `json:"status"`
		Tracks  int    `json:"tracks"`
	}
	if err := json.Unmarshal(data, &result); err != nil {
		return "", 0, err
	}

	return result.Status, result.Tracks, nil
}

// AddVideo 添加视频
func (c *Client) AddVideo(draftID, videoURL string, startTime, endTime float64, trackIndex int, volume float64) (int, string, error) {
	// 构建参数
	params := url.Values{}
	params.Set("draft_id", draftID)
	params.Set("video_url", videoURL)
	params.Set("start_time", fmt.Sprintf("%f", startTime))
	if endTime >= 0 {
		params.Set("end_time", fmt.Sprintf("%f", endTime))
	}
	if trackIndex >= 0 {
		params.Set("track_index", strconv.Itoa(trackIndex))
	}
	params.Set("volume", fmt.Sprintf("%f", volume))

	// 发送请求
	data, err := c.doRequest(http.MethodGet, "/add_video", params)
	if err != nil {
		return 0, "", err
	}

	// 解析响应
	var result struct {
		DraftID    string `json:"draft_id"`
		TrackIndex int    `json:"track_index"`
		SegmentID  string `json:"segment_id"`
	}
	if err := json.Unmarshal(data, &result); err != nil {
		return 0, "", err
	}

	return result.TrackIndex, result.SegmentID, nil
}

// AddAudio 添加音频
func (c *Client) AddAudio(draftID, audioURL string, startTime, endTime float64, trackIndex int, volume float64) (int, string, error) {
	// 构建参数
	params := url.Values{}
	params.Set("draft_id", draftID)
	params.Set("audio_url", audioURL)
	params.Set("start_time", fmt.Sprintf("%f", startTime))
	if endTime >= 0 {
		params.Set("end_time", fmt.Sprintf("%f", endTime))
	}
	if trackIndex >= 0 {
		params.Set("track_index", strconv.Itoa(trackIndex))
	}
	params.Set("volume", fmt.Sprintf("%f", volume))

	// 发送请求
	data, err := c.doRequest(http.MethodGet, "/add_audio", params)
	if err != nil {
		return 0, "", err
	}

	// 解析响应
	var result struct {
		DraftID    string `json:"draft_id"`
		TrackIndex int    `json:"track_index"`
		SegmentID  string `json:"segment_id"`
	}
	if err := json.Unmarshal(data, &result); err != nil {
		return 0, "", err
	}

	return result.TrackIndex, result.SegmentID, nil
}

// AddText 添加文本
func (c *Client) AddText(draftID, text, color string, fontSize int, duration float64, trackIndex int) (int, string, error) {
	// 构建参数
	params := url.Values{}
	params.Set("draft_id", draftID)
	params.Set("text", text)
	params.Set("color", color)
	params.Set("font_size", strconv.Itoa(fontSize))
	params.Set("duration", fmt.Sprintf("%f", duration))
	if trackIndex >= 0 {
		params.Set("track_index", strconv.Itoa(trackIndex))
	}

	// 发送请求
	data, err := c.doRequest(http.MethodGet, "/add_text", params)
	if err != nil {
		return 0, "", err
	}

	// 解析响应
	var result struct {
		DraftID    string `json:"draft_id"`
		TrackIndex int    `json:"track_index"`
		SegmentID  string `json:"segment_id"`
	}
	if err := json.Unmarshal(data, &result); err != nil {
		return 0, "", err
	}

	return result.TrackIndex, result.SegmentID, nil
}

// AddImage 添加图片
func (c *Client) AddImage(draftID, imageURL string, duration float64, trackIndex int) (int, string, error) {
	// 构建参数
	params := url.Values{}
	params.Set("draft_id", draftID)
	params.Set("image_url", imageURL)
	params.Set("duration", fmt.Sprintf("%f", duration))
	if trackIndex >= 0 {
		params.Set("track_index", strconv.Itoa(trackIndex))
	}

	// 发送请求
	data, err := c.doRequest(http.MethodGet, "/add_image", params)
	if err != nil {
		return 0, "", err
	}

	// 解析响应
	var result struct {
		DraftID    string `json:"draft_id"`
		TrackIndex int    `json:"track_index"`
		SegmentID  string `json:"segment_id"`
	}
	if err := json.Unmarshal(data, &result); err != nil {
		return 0, "", err
	}

	return result.TrackIndex, result.SegmentID, nil
}

// AddEffect 添加特效
func (c *Client) AddEffect(draftID string, trackIndex int, segmentID, effectType, effectName string, startTime, endTime float64) (string, error) {
	// 构建参数
	params := url.Values{}
	params.Set("draft_id", draftID)
	params.Set("track_index", strconv.Itoa(trackIndex))
	params.Set("segment_id", segmentID)
	params.Set("effect_type", effectType)
	params.Set("effect_name", effectName)
	params.Set("start_time", fmt.Sprintf("%f", startTime))
	if endTime >= 0 {
		params.Set("end_time", fmt.Sprintf("%f", endTime))
	}

	// 发送请求
	data, err := c.doRequest(http.MethodGet, "/add_effect", params)
	if err != nil {
		return "", err
	}

	// 解析响应
	var result struct {
		DraftID  string `json:"draft_id"`
		EffectID string `json:"effect_id"`
	}
	if err := json.Unmarshal(data, &result); err != nil {
		return "", err
	}

	return result.EffectID, nil
}

// SaveDraft 保存草稿
func (c *Client) SaveDraft(draftID string) (string, error) {
	// 构建参数
	params := url.Values{}
	params.Set("draft_id", draftID)

	// 发送请求
	data, err := c.doRequest(http.MethodGet, "/save_draft", params)
	if err != nil {
		return "", err
	}

	// 解析响应
	var result struct {
		DraftID  string `json:"draft_id"`
		DraftURL string `json:"draft_url"`
	}
	if err := json.Unmarshal(data, &result); err != nil {
		return "", err
	}

	return result.DraftURL, nil
}
